//
//  KKArticleDetailVC.m
//  DoMi
//
//  Created by 康凯 on 2016/12/5.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKArticleDetailVC.h"
#import "KKIntroductionView.h"
#import "KKCommentView.h"
#import "KKComHttp.h"
#import "KKTxtContentM.h"
#import "KKImgSectionCell.h"
#import "KKShowArticleCell.h"
#import "KKArticleDetailM.h"
#import "KKShowImgCell.h"
#import "KKStudyHttp.h"
#import "IQKeyboardManager.h"
#import "KKMyHttp.h"
@interface KKArticleDetailVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *introBtn;
@property (weak, nonatomic) IBOutlet UIButton *commentBtn;
@property (weak, nonatomic) IBOutlet UIView *container;
//简介
@property (strong, nonatomic) KKIntroductionView *introductionView;
//评论
@property (strong, nonatomic) KKCommentView *commentView;

@property(strong,nonatomic)NSArray *articleDatas;
@property(strong,nonatomic)KKArticleDetailM *articleInfo;
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *input;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *articleHeight;
@property (assign,nonatomic)float totalHeight;
@property (weak, nonatomic) IBOutlet UILabel *articleTitle;

@end

@implementation KKArticleDetailVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar=NO;
    [self setNavWhite];
//    [IQKeyboardManager sharedManager].enable = NO;
//    [self registerForKeyboardNotifications];
    if(self.articleInfo!=nil){
        [self getCommentList];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enableAutoToolbar=YES;
//    [IQKeyboardManager sharedManager].enable = YES;
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"文章详情";
    [self initNav];
    [self initView];
}

#pragma mark ---初始化nav
-(void)initNav{
    //左侧返回
    UIButton *leftBtn = [[UIButton alloc ]initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftBtn setImage:[UIImage imageNamed:@"back_blue"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    //右侧投诉
    UIButton *rightBtn = [[UIButton alloc ]initWithFrame:CGRectMake(0, 0, 40, 25)];
    [rightBtn setTitle:@"投诉" forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:13];
    [rightBtn setTitleColor:[UIColor colorWithHexString:@"#787879"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(complainClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
}

#pragma mark 初始化view
-(void)initView{
    self.introBtn.selected=YES;
    self.inputView.hidden=YES;
    //tableview
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerNib:[UINib nibWithNibName:@"KKShowArticleCell" bundle:nil] forCellReuseIdentifier:@"KKShowArticleCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"KKShowImgCell" bundle:nil] forCellReuseIdentifier:@"KKShowImgCell"];
    //简介和评论
    CGFloat viewHeight=screenHeight-332;
    self.introductionView=[[[NSBundle mainBundle] loadNibNamed:@"KKIntroductionView" owner:self options:nil] lastObject];
    self.introductionView.height=viewHeight;
    [self.introductionView initView];
    self.commentView=[[[NSBundle mainBundle] loadNibNamed:@"KKCommentView" owner:self options:nil] lastObject];
    [self.commentView initView:viewHeight];
    self.commentView.hidden=YES;
    self.introductionView.hidden=NO;
    [self.container addSubview:self.introductionView];
    [self.container addSubview:self.commentView];
    
    [self getArticleDetail];
    [self getArticleDetailInfo];
//    [self getStudyItem];
}

#pragma mark 按钮点击
#pragma mark 按钮--简介
- (IBAction)introClick:(id)sender {
    self.introBtn.selected=YES;
    self.commentBtn.selected=NO;
    self.introductionView.hidden=NO;
    self.commentView.hidden=YES;
    self.inputView.hidden=YES;
}
#pragma mark 按钮--评论
- (IBAction)commentClick:(id)sender {
    self.introBtn.selected=NO;
    self.commentBtn.selected=YES;
    self.commentView.hidden=NO;
    self.introductionView.hidden=YES;
    self.inputView.hidden=NO;
    [self getCommentList];
}
#pragma mark 按钮--投诉
-(void)complainClick{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"确定提交投诉吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self commitComplain];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 点击--返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark tableview代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.articleDatas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KKTxtContentM *content=self.articleDatas[indexPath.row];
    if([content.contenttype isEqualToString:@"0"]){
        KKShowImgCell *cell=[tableView dequeueReusableCellWithIdentifier:@"KKShowImgCell"];
        [cell initShowData:content.content];
        return cell;
    }else{
        KKShowArticleCell *cell=[tableView dequeueReusableCellWithIdentifier:@"KKShowArticleCell"];
        [cell initData:content.content];
        return cell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KKTxtContentM *content=self.articleDatas[indexPath.row];
    if([content.contenttype isEqualToString:@"0"]){
        return screenWidth-20;
    }else{
        return content.contentDetailSize.height+10;
    }
}

#pragma mark 接口--文章详情
-(void)getArticleDetail{
    [KKComHttp articleDetail:self.docId success:^(id data) {
        NSArray *list=[data objectForKey:@"listcontent"];
        NSArray *datas=[KKTxtContentM mj_objectArrayWithKeyValuesArray:list];
        self.articleDatas=datas;
        self.totalHeight=0;
        for (KKTxtContentM *content in self.articleDatas) {
            if([content.contenttype isEqualToString:@"1"]){
                self.totalHeight+=content.contentDetailSize.height+10;
            }else{
                self.totalHeight+=screenWidth-20;
            }
        }
        self.articleHeight.constant=self.totalHeight;
        self.scrollHeight.constant=screenHeight-260+self.totalHeight;
        [self.tableView reloadData];
    } failure:^(NSError *error) {

    }];
}
#pragma mark 接口--文章详情信息
-(void)getArticleDetailInfo{
    [self showDialog];
    [KKComHttp articleDetailInfo:self.docId success:^(id data) {
        self.articleInfo=data;
        self.articleTitle.text=self.articleInfo.title;
        [self getRelateArticleList];
        [self.introductionView refreshArticleData:0 setData:self.articleInfo];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark 接口--获取头部item
-(void)getStudyItem{
    NSDictionary *params=@{@"uid":self.uid,@"token":self.token};
    [KKStudyHttp getTopItem:params success:^(NSArray *datas) {
        [self.introductionView refreshData:1 setData:datas];
    } failure:^(NSError *error) {
    }];
}

#pragma mark 接口--相关课程列表
-(void)getRelateArticleList{
    [KKComHttp getRelateArticleList:self.articleInfo.articleid success:^(id data) {
        [self.introductionView refreshArticleData:2 setData:data];
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 接口--评论列表
-(void)getCommentList{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"commenttype":@"w",@"number":self.articleInfo.articleid};
    [KKStudyHttp getCommentList:params success:^(NSArray *datas) {
        [self.commentView refreshData:datas flag:@"1"];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}
#pragma mark 接口--发表评论
-(void)addComment{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"commenttype":@"w",@"number":self.articleInfo.articleid,@"commentcontent":self.input.text};
    [KKStudyHttp addComment:params success:^(id data) {
        [self dismissDialog];
        [self toast:@"评论成功"];
        self.input.text=@"";
        [self.view endEditing:YES];
        [self getCommentList];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}
#pragma mark 接口--提交投诉
-(void)commitComplain{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"type":@"w",@"number":self.articleInfo.articleid};
    [KKComHttp commitComplain:params success:^(id data) {
        [self longToast:@"已提交，谢谢您的维护，我们会尽快处理"];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark - keyboardHight
- (void)registerForKeyboardNotifications
{
    //监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil];
    //监听键盘隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden) name:UIKeyboardWillHideNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //获取键盘高度
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        self.inputView.transform=CGAffineTransformMakeTranslation(0, -kbSize.height);
    } completion:nil];
}

//当键盘隐藏的时候
- (void)keyboardHidden
{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView animateWithDuration:0 animations:^{
        self.inputView.transform=CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        self.input.text=@"";
    }];
}

- (IBAction)keyboardHiddenClick:(id)sender {
    [self.view endEditing:YES];
}

- (IBAction)sendClick:(id)sender {
    [KKMyHttp userCheck:^(id data) {
        if([KKAppUtils isEmptyString:self.input.text]){
            [self toast:@"请输入评论内容"];
            return;
        }
        [self addComment];
    } failure:^(NSError *error) {
        
    }];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



@end
